package admin

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"myai/core"
	"myai/core/types"
	"myai/handler"
	"myai/store/model"
	"myai/store/model/req"
	"myai/store/vo"
	"myai/utils"
	"myai/utils/resp"
)

type ApiKeyHandler struct {
	handler.BaseHandler
}

func NewApiKeyHandler(app *core.AppServer, db *gorm.DB) *ApiKeyHandler {
	return &ApiKeyHandler{BaseHandler: handler.BaseHandler{DB: db, App: app}}
}

// SaveOrUpdate godoc
// @Summary      添加或者更新ApiKey
// @Description  添加或者更新ApiKey
// @Tags         后台管理-ApiKey
// @Accept       json
// @Produce      json
// @Param        req   body     req.ApiKeySaveOrUpdateReq  true  "ApiKey信息"
// @Success      200  {object}  types.BizVo{date=vo.ApiKey}
// @Router       /api/admin/apikey/save_or_update [post]
// @Security AdminApiKeyAuth
func (h *ApiKeyHandler) SaveOrUpdate(c *gin.Context) {
	var data req.ApiKeySaveOrUpdateReq
	if err := c.ShouldBindJSON(&data); err != nil {
		resp.ERROR(c, types.InvalidArgs)
		return
	}
	apiKey := model.ApiKey{}
	if data.Id > 0 {
		h.DB.Find(&apiKey, data.Id)
	}
	apiKey.Value = data.Value
	apiKey.Type = data.Type
	apiKey.ApiURL = data.ApiURL
	apiKey.Enabled = data.Enabled
	apiKey.ProxyURL = data.ProxyURL
	apiKey.Name = data.Name
	// 如果数据不存在就添加，存在就修改
	err := h.DB.Save(&apiKey).Error
	if err != nil {
		resp.ERROR(c, "添加ApiKey出错："+err.Error())
		return
	}

	var keyVo vo.ApiKey
	err = utils.CopyObject(apiKey, &keyVo)
	if err != nil {
		resp.ERROR(c, "拷贝数据失败："+err.Error())
		return
	}
	keyVo.Id = apiKey.Id
	keyVo.CreatedAt = apiKey.CreatedAt.Unix()
	resp.SUCCESS(c, keyVo)
}

// List godoc
// @Summary      查询ApiKey列表
// @Description  查询ApiKey列表
// @Tags         后台管理-ApiKey
// @Accept       json
// @Produce      json
// @Param        status   query     bool  false  "是否启用"
// @Param        type   query     string  false  "类型"
// @Success      200  {object}  types.BizVo{date=[]vo.ApiKey}
// @Router       /api/admin/apikey/list [get]
// @Security AdminApiKeyAuth
func (h *ApiKeyHandler) List(c *gin.Context) {
	status := h.GetBool(c, "status")
	t := h.GetTrim(c, "type")

	session := h.DB.Session(&gorm.Session{})
	if status {
		session = session.Where("enabled", true)
	}
	if t != "" {
		session = session.Where("type", t)
	}

	var items []model.ApiKey
	var keys = make([]vo.ApiKey, 0)
	res := session.Find(&items)
	if res.Error == nil {
		for _, item := range items {
			var key vo.ApiKey
			err := utils.CopyObject(item, &key)
			if err == nil {
				key.Id = item.Id
				key.CreatedAt = item.CreatedAt.Unix()
				key.UpdatedAt = item.UpdatedAt.Unix()
				keys = append(keys, key)
			} else {
				log.Error("ApiKey查询列表拷贝数据出错：" + err.Error())
			}
		}
	}
	resp.SUCCESS(c, keys)
}

// Set godoc
// @Summary      修改某个字段
// @Description  修改某个字段
// @Tags         后台管理-ApiKey
// @Accept       json
// @Produce      json
// @Param        req   body     req.ApiKeyUpdateFiledReq  true  "要修改字段的信息"
// @Success      200  {object}  types.BizVo{}
// @Router       /api/admin/apikey/set [post]
// @Security AdminApiKeyAuth
func (h *ApiKeyHandler) Set(c *gin.Context) {
	var data req.ApiKeyUpdateFiledReq
	if err := c.ShouldBindJSON(&data); err != nil {
		resp.ERROR(c, types.InvalidArgs)
		return
	}
	err := h.DB.Model(&model.ApiKey{}).Where("id = ?", data.Id).Update(data.Filed, data.Value).Error
	if err != nil {
		resp.ERROR(c, "修改数据出错："+err.Error())
		return
	}
	resp.SUCCESS(c)
}

// Remove godoc
// @Summary      删除ApiKey
// @Description  删除ApiKey
// @Tags         后台管理-ApiKey
// @Accept       json
// @Produce      json
// @Param        id   query     int  true  "id"
// @Success      200  {object}  types.BizVo{}
// @Router       /api/admin/apikey/remove [get]
// @Security AdminApiKeyAuth
func (h *ApiKeyHandler) Remove(c *gin.Context) {
	id := h.GetInt(c, "id", 0)
	if id <= 0 {
		resp.ERROR(c, types.InvalidArgs)
		return
	}
	err := h.DB.Where("id", id).Delete(&model.ApiKey{}).Error
	if err != nil {
		resp.ERROR(c, "删除数据失败："+err.Error())
		return
	}
	resp.SUCCESS(c)
}
